package com.webdemo08.service.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.webdemo08.pojo.User;
import com.webdemo08.service.UserService;

public class UserServiceImpl implements UserService {
	private SessionFactory sessionFactory;
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	@Override
	public void addUser(User user) {
		Session session  = sessionFactory.openSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
		session.close();
	}
	@Override
	public void updateUser(User user) {
		Session session  = sessionFactory.openSession();
		session.beginTransaction();
		session.update(user);
		session.getTransaction().commit();
		session.close();
	}
	@Override
	public void deleteUser(int id) {
		Session session  = sessionFactory.openSession();
		session.beginTransaction();
		User user = (User) session.get(User.class, id);
		session.delete(user);
		session.getTransaction().commit();
		session.close();
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUsers() {
		Session session  = sessionFactory.openSession();
		session.beginTransaction();
		String hql="from User";
		List<User> users = session.createQuery(hql).list();
		session.getTransaction().commit();
		session.close();
		return users;
	}
	@Override
	public User getUser(int id) {
		Session session  = sessionFactory.openSession();
		session.beginTransaction();
		User user =(User)session.get(User.class, id);
		session.getTransaction().commit();
		session.close();
		return user;
	}
}
